package com.stn.zjx.givingtreasure.activity.dynamic;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.Image;
import android.media.ImageReader;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.TextureView;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.Gson;
import com.irozon.sneaker.Sneaker;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.activity.UserLoginActivity;
import com.stn.zjx.givingtreasure.base.BaseActivity;
import com.stn.zjx.givingtreasure.constants.StnConstants;
import com.stn.zjx.givingtreasure.domain.DynamicDetailDomain;
import com.stn.zjx.givingtreasure.domain.StatusDomain;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.net.BaseApi;
import com.stn.zjx.givingtreasure.net.impl.UserDynamicGuestNetImpl;
import com.stn.zjx.givingtreasure.net.impl.UserDynamicLikeNetImpl;
import com.stn.zjx.givingtreasure.net.impl.UserDynamicNetImpl;
import com.stn.zjx.givingtreasure.net.impl.UserFollowNetImpl;
import com.stn.zjx.givingtreasure.service.AmapLocationService;
import com.stn.zjx.givingtreasure.service.UserService;
import com.stn.zjx.givingtreasure.table.User;
import com.stn.zjx.givingtreasure.utils.SoftInputUtils;
import com.stn.zjx.givingtreasure.utils.StatusBarUtil;
import com.stn.zjx.givingtreasure.utils.ToolsUtils;
import com.vondear.rxtools.RxActivityTool;
import com.vondear.rxtools.RxImageTool;
import com.vondear.rxtools.RxNetTool;
import com.vondear.rxtools.RxSPTool;
import com.warkiz.widget.IndicatorSeekBar;
import com.warkiz.widget.OnSeekChangeListener;
import com.warkiz.widget.SeekParams;

import java.io.File;
import java.io.FileNotFoundException;
import java.nio.ByteBuffer;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;
import tv.danmaku.ijk.media.widget.media.AndroidMediaController;
import tv.danmaku.ijk.media.widget.media.IjkVideoView;

@SuppressWarnings("all")
public class DynamicVideoDetailActivity extends BaseActivity implements AMapLocationListener, IMediaPlayer.OnBufferingUpdateListener, IMediaPlayer.OnInfoListener {
    private static final int REQUEST_MEDIA_PROJECTION = 1001;
    public Integer id = 0;
    private static final int PRC_PHOTO_PICKER = 1010;
    public AmapLocationService amapLocationService = null;
    @BindView(R.id.videoView)
    IjkVideoView videoView;
    @BindView(R.id.iv_loading)
    ProgressBar ivLoading;
    @BindView(R.id.back_bt)
    RelativeLayout backBt;
    @BindView(R.id.follow_bt)
    Button followBt;
    @BindView(R.id.cir)
    CircleImageView cir;
    @BindView(R.id.open_guest)
    LinearLayout openGuest;
    @BindView(R.id.play_video)
    RelativeLayout playVideo;
    @BindView(R.id.user_nickname)
    TextView userNickname;
    @BindView(R.id.content)
    TextView content;
    @BindView(R.id.like_iv)
    ImageView likeIv;
    @BindView(R.id.like_tv)
    TextView likeTv;
    @BindView(R.id.like_bt)
    LinearLayout likeBt;
    @BindView(R.id.guest_tv)
    TextView guestTv;
    @BindView(R.id.guest_bt)
    LinearLayout guestBt;
    @BindView(R.id.hpv)
    IndicatorSeekBar hpv;
    @BindView(R.id.share_bt)
    ImageView shareBt;
    @BindView(R.id.rootView)
    RelativeLayout rootView;
    private AndroidMediaController mMediaController;
    float origin_x = 0;
    float origin_y = 0;

    DynamicDetailDomain.DataBean data = null;
    private Handler handler = new Handler();
    private boolean isFirst = true;
    public boolean isPasuse = false;
    public  int windowWidth=0;
    public int windowHeight=0;
    private int dpi=0;
    ImageReader imageReader;
    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {

    }


    @Override
    public void initComponent() {
        id = getIntent().getIntExtra("id", 0);
        mMediaController = new AndroidMediaController(this, false);
        videoView.setOnInfoListener(this);
        videoView.setBufferingUpdateListener(this);
        videoView.changeAspectRaito(0);
          WindowManager wm= (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        windowWidth = metric.widthPixels;
        windowHeight = metric.heightPixels;
        dpi = metric.densityDpi;
        videoView.setOnPreparedListener(new IMediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(IMediaPlayer iMediaPlayer) {
                 if(RxNetTool.isWifi(getApplicationContext())){
                     isPasuse = false;
                     playVideo.setVisibility(View.GONE);
                     videoView.start();
                 }else{
                     if (RxSPTool.getBoolean(getApplicationContext(), StnConstants.G3_AUTO_PLAY_VIDEO)) {
                         isPasuse = false;
                         playVideo.setVisibility(View.GONE);
                         videoView.start();
                     }
                 }


            }
        });

        videoView.setOnCompletionListener(new IMediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(IMediaPlayer iMediaPlayer) {
                iMediaPlayer.seekTo(0);
                iMediaPlayer.pause();
                playVideo.setVisibility(View.VISIBLE);
                isPasuse = true;
            }
        });
        videoView.setOnErrorListener(new IMediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(IMediaPlayer iMediaPlayer, int i, int i1) {
                playVideo.setVisibility(View.VISIBLE);
                ivLoading.setVisibility(View.GONE);
                isPasuse = false;
                return false;
            }
        });

        videoView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        origin_x = event.getX();
                        origin_y = event.getY();
                        break;
                    case MotionEvent.ACTION_UP:
                        if (origin_x == event.getX() && origin_y == event.getY()) {
                            if (!videoView.isPlaying() && isPasuse == false) {
                                System.out.println("******没有播放，没有暂停，重新播放");
                                isPasuse = false;
                                playVideo.setVisibility(View.GONE);
                                videoView.start();
                            } else if (videoView.isPlaying() && isPasuse == false) {
                                System.out.println("******播放中，没有暂停，进行暂停");
                                playVideo.setVisibility(View.VISIBLE);
                                isPasuse = true;
                                videoView.pause();
                            } else if (isPasuse == true) {
                                System.out.println("******暂停中，回复播放");
                                playVideo.setVisibility(View.GONE);
                                isPasuse = false;
                                videoView.start();

                            }
                        }
                        break;
                    default:
                        break;
                }
                return true;
            }
        });


        initInfo();
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setImmersiveStatusBar(this, false);
        setContentView(R.layout.activity_dynamic_video_detail);
        ButterKnife.bind(this);
        initComponent();
        handler.postDelayed(run, 1000);
    }

    private Runnable run = new Runnable() {
        int buffer, currentPosition, duration;

        public void run() {
            // 获得当前播放时间和当前视频的长度
            currentPosition = videoView.getCurrentPosition();
            duration = videoView.getDuration();
            //    int time = ((currentPosition * 100) / duration);
            // 设置进度条的主要进度，表示当前的播放时间
            if (hpv != null) {
                hpv.setMax(duration);
                hpv.setProgress(currentPosition);
            }
            // 设置进度条的次要进度，表示视频的缓冲进度
            buffer = videoView.getBufferPercentage();
            // seekBar.setSecondaryProgress(percent);

            handler.postDelayed(run, 1000);
        }
    };

    @OnClick({R.id.back_bt, R.id.open_guest, R.id.share_bt
    })
    public void onViewClicked(View view) {
        Bundle bundle=new Bundle();
        switch (view.getId()) {
            case R.id.back_bt:
                finish();
                break;
            case R.id.open_guest:
                User onlineUser = UserService
                        .getInstance(this)
                        .getOnlineLoginUser();
                if (onlineUser == null) {
                    RxActivityTool.skipActivity(this, UserLoginActivity.class);
                    return;
                }
                initGuestDialog();
                break;
            case R.id.share_bt:
//

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    MediaProjectionManager mMediaProjectionManager = (MediaProjectionManager)getApplication().getSystemService(Context.MEDIA_PROJECTION_SERVICE);
                    startActivityForResult(mMediaProjectionManager.createScreenCaptureIntent(), REQUEST_MEDIA_PROJECTION);
                }else{
                    Bitmap bitmap = ToolsUtils.getBitmapByView(rootView);
                    savetoImg(bitmap);
                }
                break;

        }
    }

    public void initInfo() {
        amapLocationService = new AmapLocationService(this);
        amapLocationService.registerListener(this);
        amapLocationService.start();
        User onlineUser = UserService.getInstance(this).getOnlineLoginUser();
        String token = "";
        if (onlineUser == null) {
            token = "";
        } else {
            token = onlineUser.getToken();
        }
        UserDynamicNetImpl
                .query_dynamic_detail(token, id, id + "query_dynamic_detail_" + token, new StringCallback() {
                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        if (response.isSuccessful() && !isFinishing()) {
                            initDynamicDetailResult(response.body());
                        }
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        if (response.isSuccessful() && !isFinishing()) {
                            initDynamicDetailResult(response.body());
                        }

                    }
                });

    }


    public void initGuestDialog() {
        Dialog guest_dialog;
        EditText guest_content_edit;
        guest_dialog = new Dialog(this, R.style.dialog_soft_input);
        guest_dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        guest_dialog.setContentView(R.layout.dialog_dynamic_guest_input);
        WindowManager.LayoutParams lp = guest_dialog.getWindow().getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;
        lp.gravity = Gravity.BOTTOM;
        guest_dialog.getWindow().setAttributes(lp);

        guest_content_edit = guest_dialog.findViewById(R.id.content_edit);
        TextView guest_num_count = guest_dialog.findViewById(R.id.num_count);
        TextView guest_send_guest_bt = guest_dialog.findViewById(R.id.send_guest_bt);
        View exit_bt = guest_dialog.findViewById(R.id.exit_bt);
        exit_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                guest_dialog.dismiss();
            }
        });
        guest_dialog.findViewById(R.id.rootView)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        guest_dialog.dismiss();
                    }
                });
        guest_content_edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                guest_num_count.setText(guest_content_edit.getText().length() + "/100");
                if (guest_content_edit.getText().length() == 0) {
                    guest_send_guest_bt.setBackgroundResource(R.drawable.focus_light_gray_5dp);
                    guest_send_guest_bt.setTextColor(ActivityCompat.getColor(getApplicationContext(), R.color.gray));
                    guest_send_guest_bt.setClickable(false);
                } else {
                    guest_send_guest_bt.setBackgroundResource(R.drawable.focus_theme_5dp);
                    guest_send_guest_bt.setTextColor(ActivityCompat.getColor(getApplicationContext(), R.color.white));
                    guest_send_guest_bt.setClickable(true);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        guest_send_guest_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                User onlineUser = UserService
                        .getInstance(getApplicationContext())
                        .getOnlineLoginUser();
                if (onlineUser == null) {
                    RxActivityTool.skipActivity(getApplicationContext(), UserLoginActivity.class);
                    return;
                }
                send_dynamic_guest(onlineUser.getToken(),
                        id,
                        guest_content_edit.getText().toString().trim(), guest_dialog);

            }
        });
        guest_send_guest_bt.setClickable(false);
        guest_dialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                //    guest_content_edit.getText().clear();
                // 显示软键盘
                guest_content_edit.requestFocus();
                SoftInputUtils.openSoftInput(DynamicVideoDetailActivity.this, guest_dialog.getCurrentFocus(), 50);
                if (videoView != null && videoView.isPlaying() && isPasuse == false) {
                    videoView.pause();
                    isPasuse = true;
                }

                //  SoftInputUtils.showSoftInput(DynamicDetailActivity.this,guest_dialog);
            }
        });
        guest_dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                SoftInputUtils.closedSoftInput(DynamicVideoDetailActivity.this);
//                im.hideSoftInputFromWindow(guest_content_edit.getWindowToken(),0);
                guest_content_edit.getText().clear();
                if (videoView != null && !videoView.isPlaying() && isPasuse == true) {
                    isPasuse = false;
                    videoView.start();
                }
            }
        });
        guest_dialog.show();
    }


    public void initDynamicDetailResult(String body) {
        DynamicDetailDomain domain = new Gson().fromJson(body, DynamicDetailDomain.class);
        DynamicDetailDomain.DataBean dataBean = domain.getData();
        switch (domain.getStatus()) {
            case BaseApi.REQUEST_SUCCESS_CODE:
                Glide
                        .with(DynamicVideoDetailActivity.this)
                        .asDrawable()
                        .apply(new RequestOptions().placeholder(R.mipmap.default_avatar))
                        .load(domain.getData().getDetailData().getUserAvatar())
                        .into(new SimpleTarget<Drawable>() {
                            @Override
                            public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                                cir.setImageDrawable(resource);
                            }
                        });
                userNickname.setText(domain.getData().getDetailData().getUserNickname());
                content.setText(domain.getData().getDetailData().getDynamicContent());
                DynamicVideoDetailActivity.this.data = dataBean;
                videoView.setVideoPath(domain.getData().getDetailData().getDynamicVideoPath());

                if (domain.getData().getDetailData().getIsFollow() == 0) {
                    followBt.setBackgroundResource(R.drawable.focus_blue_5dp);
                    followBt.setTextColor(ActivityCompat.getColor(getApplicationContext(), R.color.white));
                    followBt.setText(getString(R.string.follow));
                } else {
                    followBt.setBackgroundResource(R.drawable.focus_light_gray_5dp);
                    followBt.setTextColor(ActivityCompat.getColor(getApplicationContext(), R.color.gray));
                    followBt.setText(getString(R.string.already_follow));
                }


                followBt.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        User onlineUser = UserService
                                .getInstance(getApplicationContext())
                                .getOnlineLoginUser();
                        if (onlineUser == null) {
                            RxActivityTool.skipActivity(getApplicationContext(), UserLoginActivity.class);
                            return;
                        }
                        if (domain.getData().getDetailData().getIsFollow() == 0) {
                            followBt.setBackgroundResource(R.drawable.focus_light_gray_5dp);
                            followBt.setTextColor(ActivityCompat.getColor(getApplicationContext(), R.color.gray));
                            followBt.setText(getString(R.string.already_follow));
                            domain.getData().getDetailData().setIsFollow(1);
                            set_follow(onlineUser.getToken(), domain.getData().getDetailData().getUserId());
                        } else {
                            followBt.setBackgroundResource(R.drawable.focus_blue_5dp);
                            followBt.setTextColor(ActivityCompat.getColor(getApplicationContext(), R.color.white));
                            followBt.setText(getString(R.string.follow));
                            domain.getData().getDetailData().setIsFollow(0);
                            set_no_follow(onlineUser.getToken(), domain.getData().getDetailData().getUserId());
                        }
                    }
                });
                switch (domain.getData().getDetailData().getIsLike()) {
                    case 0:
                        likeIv.setImageResource(R.mipmap.love_light_gray_noselected);
                        break;
                    case 1:
                        likeIv.setImageResource(R.mipmap.love_light_gray_selected);
                        break;
                }
                likeTv.setText(String.valueOf(domain.getData().getDetailData().getLikeCount()));


                likeBt.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        User onlineUser = UserService
                                .getInstance(getApplicationContext())
                                .getOnlineLoginUser();
                        if (onlineUser == null) {
                            RxActivityTool.skipActivity(getApplicationContext(), UserLoginActivity.class);
                            return;
                        }
                        switch (domain.getData().getDetailData().getIsLike()) {
                            case 0:
                                likeIv.setImageResource(R.mipmap.love_light_gray_selected);
                                domain.getData().getDetailData().setIsLike(1);
                                set_dynamic_like(onlineUser.getToken(), domain.getData().getDetailData().getUserDynamicId());
                                likeTv.setText(String.valueOf(domain.getData().getDetailData().getLikeCount() + 1));
                                domain.getData().getDetailData().setLikeCount(domain.getData().getDetailData().getLikeCount() + 1);
                                break;
                            default:
                                likeIv.setImageResource(R.mipmap.love_light_gray_noselected);
                                domain.getData().getDetailData().setIsLike(0);
                                set_dynamic_no_like(onlineUser.getToken(), domain.getData().getDetailData().getUserDynamicId());
                                likeTv.setText(String.valueOf(domain.getData().getDetailData().getLikeCount() - 1));
                                domain.getData().getDetailData().setLikeCount(domain.getData().getDetailData().getLikeCount() - 1);
                                break;
                        }
                    }
                });
                if (domain.getData().getDetailData().getGuestCount() >= 99) {
                    guestTv.setText("99+");
                } else {
                    guestTv.setText("" + domain.getData().getDetailData().getGuestCount());
                }
                guestBt.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Bundle bundle=new Bundle();
                        bundle.putInt("id",id);
                        RxActivityTool.skipActivity(getApplicationContext(),DynamicDetailGuestListActivity.class,bundle);
                    }
                });
                hpv.setOnSeekChangeListener(new OnSeekChangeListener() {
                    @Override
                    public void onSeeking(SeekParams seekParams) {

                    }

                    @Override
                    public void onStartTrackingTouch(IndicatorSeekBar seekBar) {

                    }

                    @Override
                    public void onStopTrackingTouch(IndicatorSeekBar seekBar) {
                        videoView.seekTo(seekBar.getProgress());
                    }
                });
                break;
        }
    }


    @AfterPermissionGranted(PRC_PHOTO_PICKER)
    public void savetoImg(Bitmap bitmap) {
        String[] perms = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(this, perms)) {
            showLoading();
            // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
            File file = new File(Environment.getExternalStorageDirectory().getPath(), getString(R.string.app_name));
            if (!file.exists()) {   //判断文件夹是否存在，不存在则创建
                file.mkdirs();
            }
            String fileName = "";
            fileName = UUID.randomUUID().toString().substring(0, 4) + ".jpg";
            String com_file = file.getPath() + "/" + fileName;
            boolean isSuccess = RxImageTool.save(bitmap, com_file, Bitmap.CompressFormat.JPEG);
            if (isSuccess) {
                // 把文件插入到系统图库
                try {
                    String s = MediaStore.Images.Media.insertImage(getContentResolver(), com_file, fileName, "分享图片");

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + com_file));
                // 通知图库更新
                sendBroadcast(intent);

                ToolsUtils.shareImage(this, new File(com_file));
            } else {
                showToast("save error");
            }
            dissmissLoading();
        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.request_perssion_desc), PRC_PHOTO_PICKER, perms);
        }
    }


    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (handler != null) {
            handler.removeCallbacks(run);
        }
        if (videoView != null) {
            videoView.stopPlayback();
            videoView.release(true);

        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        if(videoView!=null&&videoView.isPlaying()&&isPasuse==false){
            System.out.println("*******************onStop");
            isPasuse=true;
            playVideo.setVisibility(View.VISIBLE);
            videoView.pause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(videoView!=null&&!videoView.isPlaying()&&isPasuse==true){
            System.out.println("*******************onResume");
            playVideo.setVisibility(View.GONE);
            isPasuse = false;
            videoView.start();
        }
    }

    int currentPosition, duration;

    @Override
    public void onBufferingUpdate(IMediaPlayer iMediaPlayer, int i) {
//        System.out.println("********************i:" + i + "*****************getCurrentPosition:" +
//                iMediaPlayer.getCurrentPosition() + ":getDuration" + iMediaPlayer.getDuration());
    }

    @Override
    public boolean onInfo(IMediaPlayer iMediaPlayer, int what, int extra) {
        switch (what) {
            case IMediaPlayer.MEDIA_INFO_BUFFERING_START://网络不好，视屏卡住了 701
                ivLoading.setVisibility(View.VISIBLE);
                break;
            case IMediaPlayer.MEDIA_INFO_BUFFERING_END://网络良好，视屏开始播放了 702
                ivLoading.setVisibility(View.GONE);
                break;
            case IMediaPlayer.MEDIA_INFO_AUDIO_RENDERING_START://每准备一次调用一次 1002

                break;
        }
        return false;
    }


    //设置关注
    public void set_follow(String token, Integer userFollowId) {
        UserFollowNetImpl
                .set_follow(token, userFollowId, token + "_set_follow_" + userFollowId, new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                    }
                });
    }

    //设置取消关注
    public void set_no_follow(String token, Integer userFollowId) {
        UserFollowNetImpl
                .set_no_follow(token, userFollowId, token + "_set_no_follow_" + userFollowId, new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                    }
                });
    }


    //设置喜欢
    public void set_dynamic_like(String token, Integer userDynamicId) {
        UserDynamicLikeNetImpl
                .set_like_dynamic(token, userDynamicId, token + "_set_like_dynamic_" + userDynamicId, new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                    }
                });
    }

    //设置不喜欢
    public void set_dynamic_no_like(String token, Integer userDynamicId) {
        UserDynamicLikeNetImpl
                .set_no_like_dynamic(token, userDynamicId, token + "_set_dynamic_no_like_" + userDynamicId, new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                    }
                });
    }

    //发送动态评论
    public void send_dynamic_guest(String token, Integer userDynamicId,
                                   String userDynamicGuestContent, Dialog dialog) {
        UserDynamicGuestNetImpl
                .send_dynamic_guest(token, userDynamicId, userDynamicGuestContent,
                        token + "_send_dynamic_guest_" + userDynamicId,
                        new StringCallback() {
                            @Override
                            public void onStart(Request<String, ? extends Request> request) {
                                super.onStart(request);
                                showLoading();
                            }

                            @Override
                            public void onFinish() {
                                super.onFinish();
                                dissmissLoading();
                            }

                            @Override
                            public void onSuccess(Response<String> response) {
                                if (response.isSuccessful() && !isFinishing()) {
                                    StatusDomain domain = new Gson().fromJson(response.body(), StatusDomain.class);
                                    switch (domain.getStatus()) {
                                        case BaseApi.REQUEST_SUCCESS_CODE:
                                            dialog.dismiss();
                                            User onlineUser = UserService.getInstance(getApplicationContext()).getOnlineLoginUser();
                                            String token = "";
                                            if (onlineUser == null) {
                                                token = "";
                                            } else {
                                                token = onlineUser.getToken();
                                            }
                                            if (TextUtils.isEmpty(guestTv.getText().toString())) {
                                                guestTv.setText("1");

                                            } else {
                                                int count = Integer.parseInt(guestTv.getText().toString());
                                                count++;
                                                guestTv.setText(String.valueOf(count));
                                            }


//                                            Sneaker.with(DynamicVideoDetailActivity.this)
//                                                    .autoHide(true)
//                                                    .setTitle("" + domain.getMessage(), R.color.white)
//                                                    .sneakSuccess();
                                            break;
                                        default:
//                                            Sneaker.with(DynamicVideoDetailActivity.this)
//                                                    .autoHide(true)
//                                                    .setTitle("" + domain.getMessage(), R.color.white)
//                                                    .sneakError();
                                            showToast(domain.getMessage());
                                            break;
                                    }

                                }
                            }
                        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        MediaProjectionManager mMediaProjectionManager = (MediaProjectionManager)getApplication().getSystemService(Context.MEDIA_PROJECTION_SERVICE);
           if(resultCode!=RESULT_OK){
               return;
           }
           switch (requestCode){
               case REQUEST_MEDIA_PROJECTION:
                 showLoading();
               MediaProjection mMediaProjection = mMediaProjectionManager.getMediaProjection(resultCode, data);
                   imageReader = ImageReader.newInstance(windowWidth, windowHeight, 0x1, 2); //ImageFormat.RGB_565
                VirtualDisplay mVirtualDisplay = mMediaProjection.createVirtualDisplay("screen-mirror",
                           windowWidth, windowHeight, dpi,       DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                        imageReader.getSurface(), null, null);
                   startCapture();
                   break;
           }
    }

    private void startCapture() {
        SystemClock.sleep(1000);
      String  imageName = System.currentTimeMillis() + ".png";
        Image image = imageReader.acquireNextImage();
        if (image == null) {
            dissmissLoading();
            return;
        }
        int width = image.getWidth();
        int height = image.getHeight();
        final Image.Plane[] planes = image.getPlanes();
        final ByteBuffer buffer = planes[0].getBuffer();
        int pixelStride = planes[0].getPixelStride();
        int rowStride = planes[0].getRowStride();
        int rowPadding = rowStride - pixelStride * width;
       Bitmap bitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888);
        bitmap.copyPixelsFromBuffer(buffer);
        image.close();

        if (bitmap != null) {
            savetoImg(bitmap);
        }else{
          showToast("no save");
        }
        dissmissLoading();
    }
}
